<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选课中心 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .filter-box {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .filter-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
        }

        .filter-item {
            display: flex;
            align-items: center;
        }

        .filter-item label {
            margin-right: 10px;
            color: #555;
            font-weight: 500;
        }

        .filter-item select,
        .filter-item input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .filter-actions {
            display: flex;
            justify-content: flex-end;
        }

        .filter-btn {
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .filter-btn.reset {
            background-color: #95a5a6;
            margin-right: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        table th,
        table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        table th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        table tr:hover {
            background-color: #f5f5f5;
        }

        .course-status {
            font-weight: 600;
        }

        .course-status.open {
            color: #27ae60;
        }

        .course-status.full {
            color: #e74c3c;
        }

        .course-status.selected {
            color: #3498db;
        }

        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            color: white;
        }

        .action-btn.select {
            background-color: #27ae60;
        }

        .action-btn.unselect {
            background-color: #e74c3c;
        }

        .action-btn.detail {
            background-color: #3498db;
        }

        .action-btn:hover {
            opacity: 0.9;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 60%;
            max-width: 600px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #333;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }

        .info-item {
            margin-bottom: 10px;
        }

        .info-label {
            font-weight: 600;
            color: #555;
            margin-bottom: 5px;
        }

        .info-value {
            color: #333;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span id="sidebar-student-name">学生</span> - <span th:text="${session.user.role}">学生</span>
                </div>
            </div>
            <ul class="menu">
                <li><a href="/student/dashboard">我的概览</a></li>
                <li class="active"><a href="/student/courses">选课中心</a></li>
                <li><a href="/student/schedule">我的课表</a></li>
                <li><a href="/student/grades">我的成绩</a></li>
                <li><a href="/student/profile">个人信息</a></li>
            </ul>
            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>选课中心</h1>
            </div>

            <div class="filter-box">
                <div class="filter-group">
                    <div class="filter-item">
                        <label for="semester">学期</label>
                        <select id="semester" name="semester">
                            <option value="all">全部学期</option>
                            <option value="大一上">大一上</option>
                            <option value="大一下">大一下</option>
                            <option value="大二上" selected>大二上</option>
                            <option value="大二下">大二下</option>
                            <option value="大三上">大三上</option>
                            <option value="大三下">大三下</option>
                            <option value="大四上">大四上</option>
                            <option value="大四下">大四下</option>
                        </select>
                    </div>
                    <div class="filter-item">
                        <label for="courseType">课程类型</label>
                        <select id="courseType" name="courseType">
                            <option value="all">全部类型</option>
                            <option value="必修课">必修课</option>
                            <option value="选修课">选修课</option>
                            <option value="公选课">公选课</option>
                        </select>
                    </div>
                    <div class="filter-item">
                        <label for="keyword">关键词</label>
                        <input type="text" id="keyword" name="keyword" placeholder="课程名称或编号">
                    </div>
                    <div class="filter-item">
                        <label for="status">状态</label>
                        <select id="status" name="status">
                            <option value="all">全部</option>
                            <option value="open">可选</option>
                            <option value="selected">已选</option>
                        </select>
                    </div>
                </div>
                <div class="filter-actions">
                    <button class="filter-btn reset" onclick="resetFilters()">重置</button>
                    <button class="filter-btn" onclick="searchCourses()">筛选</button>
                </div>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>课程编号</th>
                        <th>课程名称</th>
                        <th>学分</th>
                        <th>开课学期</th>
                        <th>授课教师</th>
                        <th>课程类型</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="courseList">
                    <!-- 课程数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 课程详情模态框 -->
    <div id="courseDetailModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>课程详情</h2>
                <span class="close" onclick="closeDetailModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-label">课程编号</div>
                        <div class="info-value" id="detail-courseId"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">课程名称</div>
                        <div class="info-value" id="detail-name"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">学分</div>
                        <div class="info-value" id="detail-credit"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">总学时</div>
                        <div class="info-value" id="detail-totalHours"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">开课学期</div>
                        <div class="info-value" id="detail-semester"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">授课教师</div>
                        <div class="info-value" id="detail-teacher"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">教室</div>
                        <div class="info-value" id="detail-classroom"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">专业</div>
                        <div class="info-value" id="detail-major"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">课程类型</div>
                        <div class="info-value" id="detail-courseType"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">开课年份</div>
                        <div class="info-value" id="detail-year"></div>
                    </div>
                </div>
                <div class="info-item" style="margin-top: 20px;">
                    <div class="info-label">课程描述</div>
                    <div class="info-value" id="detail-description"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时获取课程数据
        document.addEventListener('DOMContentLoaded', function () {
            fetchStudentInfo();
            searchCourses();
        });

        // 获取学生信息
        function fetchStudentInfo() {
            fetch('/api/student/info')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取学生信息失败') });
                    }
                    return response.json();
                })
                .then(student => {
                    // 更新侧边栏显示的学生姓名
                    document.getElementById('sidebar-student-name').textContent = student.name;
                })
                .catch(error => {
                    console.error('获取学生信息出错:', error);
                });
        }

        // 搜索课程
        function searchCourses() {
            const semester = document.getElementById('semester').value;
            const courseType = document.getElementById('courseType').value;
            const keyword = document.getElementById('keyword').value;
            const status = document.getElementById('status').value;

            // 构建API请求URL
            let url = `/api/student/courses/available?semester=${semester}&courseType=${courseType}`;
            if (keyword) {
                url += `&keyword=${encodeURIComponent(keyword)}`;
            }

            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        }
                        return response.text().then(text => { throw new Error(text || '获取课程失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    renderCourseList(data, status);
                })
                .catch(error => {
                    console.error('获取课程出错:', error);
                    alert(`获取课程失败: ${error.message}`);
                });
        }

        // 渲染课程列表
        function renderCourseList(coursesWithStatus, statusFilter) {
            const tableBody = document.getElementById('courseList');
            tableBody.innerHTML = '';

            // 根据状态筛选
            let filteredCourses = coursesWithStatus;
            if (statusFilter !== 'all') {
                filteredCourses = coursesWithStatus.filter(item => item.status === statusFilter);
            }

            if (filteredCourses.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `<td colspan="8" style="text-align: center;">没有符合条件的课程</td>`;
                tableBody.appendChild(emptyRow);
                return;
            }

            filteredCourses.forEach(item => {
                const course = item.course;
                const status = item.status;

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${course.courseId}</td>
                    <td>${course.name}</td>
                    <td>${course.credit}</td>
                    <td>${course.semester}</td>
                    <td>${course.teacher ? course.teacher.name : '未知'}</td>
                    <td>${course.courseType}</td>
                    <td>
                        <span class="course-status ${status === 'selected' ? 'selected' : 'open'}">
                            ${status === 'selected' ? '已选' : '可选'}
                        </span>
                    </td>
                    <td>
                        ${status === 'selected' ?
                        `<button class="action-btn unselect" onclick="unselectCourse('${course.courseId}')">退选</button>` :
                        `<button class="action-btn select" onclick="selectCourse('${course.courseId}')">选课</button>`
                    }
                        <button class="action-btn detail" onclick="showCourseDetail('${course.courseId}')">详情</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 选课
        function selectCourse(courseId) {
            fetch(`/api/student/courses/select/${courseId}`, {
                method: 'POST'
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 409) {
                            alert('已经选过该课程');
                            throw new Error('已经选过该课程');
                        } else if (response.status === 404) {
                            alert('课程不存在');
                            throw new Error('课程不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '选课失败') });
                    }
                    return response.json();
                })
                .then(() => {
                    alert('选课成功');
                    searchCourses(); // 刷新课程列表
                })
                .catch(error => {
                    console.error('选课出错:', error);
                    alert(`选课失败: ${error.message}`);
                });
        }

        // 退选
        function unselectCourse(courseId) {
            if (!confirm('确定要退选此课程吗？')) {
                return;
            }

            fetch(`/api/student/courses/unselect/${courseId}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('未选择该课程');
                            throw new Error('未选择该课程');
                        } else if (response.status === 400) {
                            alert('已有成绩的课程不能退选');
                            throw new Error('已有成绩的课程不能退选');
                        }
                        return response.text().then(text => { throw new Error(text || '退选失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    alert('退选成功');
                    searchCourses(); // 刷新课程列表
                })
                .catch(error => {
                    console.error('退选出错:', error);
                    alert(`退选失败: ${error.message}`);
                });
        }

        // 显示课程详情
        function showCourseDetail(courseId) {
            fetch(`/api/student/course/${courseId}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 404) {
                            alert('课程不存在');
                            throw new Error('课程不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '获取课程详情失败') });
                    }
                    return response.json();
                })
                .then(course => {
                    // 填充课程详情
                    document.getElementById('detail-courseId').textContent = course.courseId;
                    document.getElementById('detail-name').textContent = course.name;
                    document.getElementById('detail-credit').textContent = course.credit;
                    document.getElementById('detail-totalHours').textContent = course.totalHours;
                    document.getElementById('detail-semester').textContent = course.semester;
                    document.getElementById('detail-teacher').textContent = course.teacher ? course.teacher.name : '未知';
                    document.getElementById('detail-classroom').textContent = course.classroom ?
                        `${course.classroom.building} - ${course.classroom.classroomId}` : '未知';
                    document.getElementById('detail-major').textContent = course.major;
                    document.getElementById('detail-courseType').textContent = course.courseType;
                    document.getElementById('detail-year').textContent = course.year;
                    document.getElementById('detail-description').textContent = course.description || '无描述';

                    // 显示模态框
                    document.getElementById('courseDetailModal').style.display = 'block';
                })
                .catch(error => {
                    console.error('获取课程详情出错:', error);
                    alert(`获取课程详情失败: ${error.message}`);
                });
        }

        // 关闭课程详情模态框
        function closeDetailModal() {
            document.getElementById('courseDetailModal').style.display = 'none';
        }

        // 重置筛选条件
        function resetFilters() {
            document.getElementById('semester').value = '大二上';
            document.getElementById('courseType').value = 'all';
            document.getElementById('keyword').value = '';
            document.getElementById('status').value = 'all';
            searchCourses();
        }
    </script>
</body>

</html>